<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="优惠券">
        <el-select v-model="couponId" style="width:550px">
          <el-option v-for="item in couponList" :key="item.id"
            :label="item.couponName + '(' + item.promotionName + '从' + item.startTime + '至' + item.endTime + ')'" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称：" prop="purchaserName">
        <el-input v-model="queryParams.paramMap.purchaserName" />
      </el-form-item>
      <el-form-item label="客户编号：" prop="businessCode">
        <el-input v-model="queryParams.paramMap.businessCode" />
      </el-form-item>
      <el-form-item label="采购员名称：" prop="memberName">
        <el-input v-model="queryParams.memberName" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['store:promotion:coupon:member:add']">派发</el-button>
        <el-button type="primary" plain icon="el-icon-magic-stick" size="mini" @click="handleImport"
          v-hasPermi="['store:promotion:coupon:member:import']">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table border v-loading="loading" :data="memberCouponList"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户名称" prop="purchaserName" width="200" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="客户编号" prop="businessCode" width="100" align="center" />
      <el-table-column label="开始时间" prop="startTime" align="center" width="160" />
      <el-table-column label="结束时间" prop="endTime" align="center" width="160" />
      <el-table-column label="消费门槛数量" prop="consumeQuantity" :show-overflow-tooltip="true"
        width="100" align="center" />
      <el-table-column label="消费门槛金额" prop="consumeThreshold" :show-overflow-tooltip="true"
        width="100" align="center" />
      <el-table-column label="面值" prop="price" width="80" align="center" />
      <el-table-column label="折扣" prop="discount" width="80" align="center" />
      <el-table-column label="状态" align="center" prop="memberCouponStatus" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.member_coupon_status"
            :value="scope.row.memberCouponStatus" />
        </template>
      </el-table-column>
      <el-table-column label="活动描述" prop="description" width="200" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.memberCouponStatus === 'NEW'">
          <el-button type="danger" plain size="small" @click="toVoid(scope.row)"
          v-hasPermi="['store:promotion:coupon:member:cancel']"> 作废 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 派发优惠券对话框 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title" :visible.sync="open" append-to-body>
      <div class="DistributionCouponTitle">&nbsp;优惠券：<span>{{DistributionCouponTitle}}</span> </div>
      <el-form ref="form" :model="form" :inline="true">
        <el-form-item label="客户名称：" prop="purchaserName" :show-overflow-tooltip="true">
          <el-input v-model="form.purchaserName" style="width:200px" />
        </el-form-item>
        <el-form-item label="客户编号：" prop="businessCode" :show-overflow-tooltip="true">
          <el-input v-model="form.businessCode" style="width:200px" />
        </el-form-item>
        <el-form-item label="登录账号：" prop="username" :show-overflow-tooltip="true">
          <el-input v-model="form.username" style="width:200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery1">搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery1">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table border v-loading="loading1" :data="orderList" @selection-change="DistributionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="客户名称" prop="purchaserName" width="350" align="left" />
        <el-table-column label="客户编号" prop="businessCode" width="100" align="left" />
        <el-table-column label="登录账号" prop="username" width="120" align="center" />
        <el-table-column label="采购员姓名" prop="memberName" width="100" align="center" />
        <el-table-column label="客户类型" prop="mold" width="100" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.purchaser_certified_mold" :value="scope.row.mold" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total1>0" :total="total1" :page.sync="form.pageNum"
        :limit.sync="form.pageSize" @pagination="handleQuery1" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 赠送 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="提示" :visible.sync="open2" width="300px">
      <span>确认赠送吗</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open2 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm2">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 作废 -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag title="提示" :visible.sync="open1" width="300px">
      <span>确认作废吗</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open1 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm1">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 导入 -->
    <!-- /dev-api/store/promotion/coupon/{couponId}/memberCoupons/importData -->
    <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title" :visible.sync="dialogVisible" width="21%">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="headers" :action="
      r + '/store/promotion/coupon/' + couponId + '/memberCoupons/importData'"
        :disabled="isUploading" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或 <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false"
            style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list } from "@/api/purchaser/purchaser"
import { listCoupon } from "@/api/promotion/config"
import { getToken } from "@/utils/auth"
import { listMemberCoupons, addMemberCoupons, voidCoupon } from "@/api/promotion/memberCoupon"

export default {
  name: "CouponGive",
  dicts: ["member_coupon_status", "purchaser_certified_mold"],
  data () {
    return {
      //优惠券列表
      couponList: [],
      // 遮罩层
      loading: false,
      loading1: false,
      // 是否显示弹出层
      open: false,
      open1: false,
      open2: false,
      dialogVisible: false,
      // 弹出层标题
      title: "",
      // 列表
      memberCouponList: [],
      // 总条数
      total: 0,
      total1: 0,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paramMap: {
          purchaserName: undefined,
          businessCode: undefined
        }
      },
      // 派发 搜索
      form: {
        pageNum: 1,
        pageSize: 10
      },
      // 派发优惠券 信息
      DistributionCouponTitle: '',
      // 派发 搜索会员的列表
      orderList: [],
      row: {},
      row1: {},
      couponId: '',
      files: [],
      id: '',
      r: process.env.VUE_APP_BASE_API,
      isUploading: false,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  created () {
    //获取优惠券列表
    this.getCouponList();
    this.getList()
  },
  methods: {
    getCouponList () {
      const param = { getType: 'DISTRIBUTE,NEWCOMER', paramMap: { valid: true, beginEndTime: this.parseTime(new Date())} }
      listCoupon(param).then(response => {
        this.couponList = response.rows
        // if (this.couponList && this.couponList.length > 0) {
        //   this.queryParams.couponId = this.couponList[0].id
        // }
        this.couponList.forEach(item=>{
          if(item.consumeThreshold){
            item.promotionName += "-满" + item.consumeThreshold + "元可用"
          }else{
            item.promotionName += "-满" + item.consumeQuantity + "可用"
          }
        })
      })
    },
    /** 查询会员优惠券列表 */
    getList () {
      this.loading = true;
      this.queryParams.couponId = this.couponId;
      listMemberCoupons(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.memberCouponList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 作废
    toVoid (row) {
      this.row1 = row
      this.open1 = true
    },
    // 派发 选中
    DistributionChange (val) {
      this.row = val[0]
    },
    // 确定按钮
    submitForm () {
      if (this.row.memberId) {
        this.open2 = true
      }
    },
    // 确定 作废
    submitForm1 () {
      voidCoupon(this.row1.id).then(res => {
        if (res.code === 200) {
          this.open1 = false;
          this.$modal.msgSuccess("成功")
          this.getList()
        }
      })
    },
    // 确定 赠送
    submitForm2 () {
      addMemberCoupons({ couponId: this.couponId, memberId: this.row.memberId, memberName: this.row.memberName }).then(res => {
        if (res.code === 200) {
          this.open = false
          this.open2 = false
          this.handleQuery()
        }
      })
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 派发内 搜索按钮
    handleQuery1 () {
      list(this.form).then(response => {
        this.orderList = response.rows;
        this.total1 = response.total;
        this.loading1 = false;
      })
    },

    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams = { pageNum: 1, pageSize: 10 }
      this.couponId = ''
      this.handleQuery();
    },
    /** 派发内  重置按钮操作 */
    resetQuery1 () {
      this.form = {}
      this.orderList = []
    },

    /** 新增按钮操作 */
    handleAdd () {
      // 选中优惠券 之后
      if (this.couponId) {
        // this.reset()
        this.open = true
        this.title = "赠送优惠券"
        this.couponList.forEach(i => {
          if (i.id === this.couponId) {
            this.DistributionCouponTitle = i.couponName + '(' + i.promotionName + ')'
          }
        })
      }
    },


    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.dialogVisible = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 下载模板
    importTemplate () {
      this.download(
        "store/promotion/coupon/memberCoupons/importTemplate",
        {},
        `派发优惠券模板_${this.parseTime(new Date().getTime(), "{y}-{m}-{d}_{h}{i}{s}")}.xlsx`
      );
    },
    handleImport () {
      if (this.couponId) {
        this.dialogVisible = true
        this.title = "导入"
      }
    },
    handleUpload (raw) {
      this.files.push(raw.file)
    },
    handFileSuccess (file) {
      this.files = []
      this.$refs.upload.clearFiles();
    },
    handleRemove (file, fileList) {
      this.files = fileList
    },
    beforeRemove (file, fileList) {
      console.log(file, fileList);
    },
    //
    handleSelectionChange () { },
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  top: 0;
  .el-dialog__body {
    padding-top: 0;
    padding-bottom: 0;
    .DistributionCouponTitle {
      padding: 10px 10px 10px 20px;
      font-weight: 700;
      span {
        margin-left: 20px;
      }
    }
  }
}
</style>
